<template>
  <div>
    <!-- 通知头部 -->
    <div class="notifications-header">
      <div class="notifications-back">
        <div class="back-button" @click="goBack()">
          <svg t="1742876602916" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
            p-id="3194" width="20" height="20">
            <path
              d="M277.382 553.022c-23.136-22.633-23.113-59.378 0.024-82.035l383.961-421.98c23.16-22.657 60.65-22.68 83.786-0.048 23.112 22.657 23.088 59.378-0.048 82.058l-347.407 381.779 346.713 381.035c23.16 22.681 23.401 59.186 0.576 81.555-22.825 22.368-60.122 22.104-83.258-0.553l-383.052-420.97c-0.382-0.361-0.91-0.457-1.294-0.84z"
              fill="#1296db" p-id="3195"></path>
          </svg>
        </div>
      </div>
      <div class="notifications-title">通知消息</div>
      <div style="width: 24px;"></div> <!-- 占位，保持标题居中 -->
    </div>
    
    <!-- 选项卡导航 -->
    <div class="tab-navigation">
      <div class="tab-item" :class="{ 'active': activeTab === 'message' }" @click="activeTab = 'message'">
        我的消息
      </div>
      <div class="tab-item" :class="{ 'active': activeTab === 'system' }" @click="activeTab = 'system'">
        系统通知
      </div>
    </div>

    <!-- 内容区域 -->
        <!-- 这里通过 key 强制重新渲染很关键 -->
    <div class="content" :key="activeTab"
        v-infinite-scroll="activeTab=='message' ? loadMore_messageNotifications : loadMore_systemNotifications" 
        :infinite-scroll-immediate="false" 
        :infinite-scroll-delay="200"
        :infinite-scroll-distance="10">
      <!-- 无通知时显示 -->
      <div v-if="filteredNotifications.length === 0" class="empty-notifications">
        <div class="empty-icon">
          <i class="fas fa-bell-slash"></i>
        </div>
        <div v-if="userStoreObject.userInfo.id != null && userStoreObject.userInfo.id != ''" class="empty-text">
          {{ activeTab === 'system' ? '暂无系统通知' : '暂无我的消息' }}
        </div>
        <div v-else class="empty-text">
          请登录后查看我的消息
        </div>
      </div>

      <!-- 通知列表 -->
      <div v-else class="notifications-list">
        <div v-for="(notification, index) in filteredNotifications" :key="index" class="notification-item" 
             :class="{'unread': !notification.isRead && notification.isRead != undefined}"
             @click="markAsRead(notification)">
          <div class="notification-icon">
            <i class="fas" :class="getNotificationIcon()"></i>
          </div>
          <div class="notification-content">
            <div class="notification-title">{{ notification.sender }}</div>
            <div class="notification-message">{{ notification.content }}</div>
            <div class="notification-time">{{ formatTimeAgo(notification.createTime) }}</div>
          </div>
          <div v-if="!notification.isRead && notification.isRead != undefined" class="unread-indicator"></div>
          <div v-if="activeTab === 'message' && notification.isRead" class="delete-button" @click.stop="deleteNotification(notification)">
            <i class="fas fa-trash"></i>
          </div>
        </div>
      </div>

      
      <!-- 删除已读消息按钮 (仅在"我的消息"选项卡且有已读消息时显示) -->
      <!-- <div v-if="activeTab === 'message' && hasReadMessages" class="clear-all-button" @click="deleteAllReadMessages">
        删除全部已读消息
      </div> -->

          <!-- 确认删除弹窗 -->
      <div class="confirm-dialog" v-if="showDeleteConfirm">
        <div class="confirm-dialog-content">
          <div class="confirm-dialog-title">确认删除</div>
          <div class="confirm-dialog-message">确定要删除这条消息吗？</div>
          <div class="confirm-dialog-buttons">
            <button class="cancel-button" @click="cancelDelete">取消</button>
            <button class="confirm-button" @click="confirmDelete">确认</button>
          </div>
        </div>
      </div>

    </div>


  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import api from '@/api';
import { UserStore } from '@/stores/userInfoStore';

const router = useRouter();
const userStoreObject = UserStore();


const activeTab = ref('message'); // 当前激活的选项卡
const current_1 = ref(1);
const size_1 = ref(10);
const total_1 = ref(0);
const loading_1 = ref(false); // 加载状态
const isHasMore_1 = ref(true); // 是否还有更多消息

const current_2 = ref(1);
const size_2 = ref(10);
const total_2 = ref(0);
const loading_2 = ref(false);
const isHasMore_2 = ref(true);

// 确认删除弹窗相关状态
const showDeleteConfirm = ref(false);
const notificationToDelete = ref(null); // 存储待删除的通知


const systemNotifications = ref([]); // 系统通知数据
const messageNotifications = ref([]); // 我的消息数据



// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 根据当前选项卡获取对应图标
const getNotificationIcon = () => {
  return activeTab.value === 'system' ? 'fa-cog' : 'fa-envelope';
};

// 标记某条通知为已读
const markAsRead = (notification) => {
  if(notification.isRead != undefined && notification.isRead != true){
    notification.isRead = true;
    api.markNoticeAsRead(notification.id, userStoreObject.userInfo.id)
  }
};

// 格式化时间显示
function formatTimeAgo(timeStr) {
  
  const time = new Date(timeStr); // 将传入的时间对象转换为 Date 对象
  const now = new Date(); // 获取当前时间
  const diff = now.getTime() - time.getTime();// 计算时间差（单位：毫秒）

  // 将时间差转换为分钟、小时、天
  const minutes = Math.floor(diff / 1000 / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  // 根据时间差返回对应的时间格式
  if (days > 7) {
    return "7天前";
  } else if (days > 0) {
    return `${days}天前`;
  } else if (hours > 0) {
    return `${hours}小时前`;
  } else if (minutes > 0) {
    return `${minutes}分钟前`;
  } else {
    return "刚刚";
  }
}

// 根据选中的选项卡获取对应的通知数组
const filteredNotifications = computed(() => {
  return activeTab.value === 'system' ? systemNotifications.value : messageNotifications.value;
});

// 删除已读通知
const deleteNotification = (notification) => {
  // 显示确认弹窗并存储待删除的通知
  showDeleteConfirm.value = true;
  notificationToDelete.value = notification;
};

// 确认删除
const confirmDelete = () => {
  if (notificationToDelete.value) {
    const index = messageNotifications.value.findIndex(item => item.id === notificationToDelete.value.id);
    if (index !== -1) {
      messageNotifications.value.splice(index, 1);
      api.deleteReadNotice(notificationToDelete.value.id);
    }
    // 关闭确认弹窗
    showDeleteConfirm.value = false;
    notificationToDelete.value = null;
  }
};

// 取消删除
const cancelDelete = () => {
  showDeleteConfirm.value = false;
  notificationToDelete.value = null;
};

// 加载“我的消息”数据
const loadMore_messageNotifications = async()=>{
  if(isHasMore_1.value && loading_1.value == false){
    loading_1.value = true;
    current_1.value++;
    await api.getNoticeByUserId(userStoreObject.userInfo.id, current_1.value, size_1.value).then(res => {
      messageNotifications.value = messageNotifications.value.concat(res.data.data.list)
      loading_1.value = false;
      if(res.data.data.list.length < 10){
        isHasMore_1.value = false; //  没有更多数据
      }
    })
  }
}

// 加载“系统通知”数据
const loadMore_systemNotifications = async()=>{
  if(isHasMore_2.value && loading_2.value == false){
    loading_2.value = true;
    current_2.value++;
    await api.getGlobalNotice(current_2.value, size_2.value).then(res => {
      systemNotifications.value = systemNotifications.value.concat(res.data.data.list)
      loading_2.value = false;
      if(res.data.data.list.length < 10){
        isHasMore_2.value = false; //  没有更多数据
      }
    })
  }
}


onMounted(async() => {

  if(userStoreObject.userInfo.id != null && userStoreObject.userInfo.id != ''){
    //获取我的消息
    api.getNoticeByUserId(userStoreObject.userInfo.id, current_1.value, size_1.value).then(res => {
      total_1.value = res.data.data.total;
      if(total_1.value < 10){
        isHasMore_1.value = false;
      }
      messageNotifications.value = res.data.data.list
    })
  }

  //获取系统通知
  api.getGlobalNotice(current_1.value, size_1.value).then(res => {
    total_2.value = res.data.data.total;
    if(total_2.value < 10){
      isHasMore_2.value = false;
    }
    systemNotifications.value = res.data.data.list
  })

});

</script>

<style lang="scss" scoped>
.notifications-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
}

.notifications-title {
  font-size: 18px;
  font-weight: 600;
}

.back-button {
  display: flex;
  align-items: center;
}

.content {
  height: calc(100vh - 150px);
  overflow: auto;
  padding: 16px;
}

.empty-notifications {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.empty-icon {
  font-size: 48px;
  color: #ccc;
  margin-bottom: 16px;
}

.empty-text {
  color: #999;
  font-size: 16px;
}

.notifications-list {
  margin-top: 16px;
}

.notification-item {
  display: flex;
  padding: 16px;
  border: 1px solid #eaeaea;
  position: relative;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.notification-item.unread {
  background-color: #f0f7ff;
}

.notification-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e6f2ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: #007aff;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-weight: 600;
  margin-bottom: 4px;
  font-size: 16px;
}

.notification-message {
  color: #666;
  margin-bottom: 15px;
  font-size: 14px;
  line-height: 1.4;
}

.notification-time {
  color: #999;
  font-size: 12px;
}

.unread-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #007aff;
  position: absolute;
  top: 16px;
  right: 16px;
}

.tab-navigation {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
  margin-bottom: 8px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 14px;
  color: #666;
  position: relative;
  cursor: pointer;
}

.tab-item.active {
  color: #007aff;
  font-weight: 600;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 3px;
  background-color: #007aff;
  border-radius: 3px;
}

.foot-bar {
  height: 80px;
}

.delete-button {
  position: absolute;
  right: 16px;
  bottom: 16px;
  color: #ff3b30;
  font-size: 15px;
  cursor: pointer;
}

.delete-button:hover {
  opacity: 0.8;
}

.clear-all-button {
  margin-top: 20px;
  text-align: center;
  padding: 12px;
  background-color: #f8f8f8;
  color: #ff3b30;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.clear-all-button:active {
  background-color: #f0f0f0;
}

/* 确认删除弹窗样式 */
.confirm-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.confirm-dialog-content {
  width: 80%;
  max-width: 300px;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: dialog-fade-in 0.3s;
}

@keyframes dialog-fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.confirm-dialog-title {
  padding: 16px;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
  border-bottom: 1px solid #eaeaea;
}

.confirm-dialog-message {
  padding: 20px 16px;
  text-align: center;
  color: #666;
  font-size: 16px;
}

.confirm-dialog-buttons {
  display: flex;
  border-top: 1px solid #eaeaea;
}

.cancel-button, .confirm-button {
  flex: 1;
  padding: 14px 0;
  text-align: center;
  font-size: 16px;
  border: none;
  background: none;
  cursor: pointer;
}

.cancel-button {
  color: #666;
  border-right: 1px solid #eaeaea;
}

.confirm-button {
  color: #007aff;
  font-weight: 600;
}

.cancel-button:active, .confirm-button:active {
  background-color: #f5f5f5;
}
</style>